#include <common.h>
#include "i2c2.h"

int i2c2::i2cfd = 0;

int i2c2::i2c2_init()
{
     // open i2c-2 device
    i2cfd = open(I2C2_DEV_NAME, O_RDWR);
    if (i2cfd < 0) {
        cout << "i2c-2 Can't open !" << endl;
        return -1;
    }

    // 设置适配器收不到ACK时重试的次数 默认为1
    if (ioctl(i2cfd, I2C_RETRIES, 1) < 0) {
        close(i2cfd);
        i2cfd = 0;
        cout << "set i2c-2 retry fail!" << endl;
        return -1;
    }

    // 设置超时时间 10ms作为一个单元  这里设置等待100ms ，后面要改进
    if (ioctl(i2cfd, I2C_TIMEOUT, 10) < 0) {
        close(i2cfd);
        i2cfd = 0;
        cout << "set i2c-2 timeout fail!" << endl;
        return -1;
    }
    printf("i2c2 init success!\n");
    return 0;
}

int i2c2::i2c_write(unsigned char slave, unsigned char reg, unsigned char value)
{
    int ret;
    struct i2c_rdwr_ioctl_data ssm_msg = {0};
    unsigned char buf[2] = {0};
    ssm_msg.nmsgs = 1;
    ssm_msg.msgs = (struct i2c_msg *)malloc(ssm_msg.nmsgs * sizeof(struct i2c_msg));
    if (ssm_msg.msgs == NULL) {
        cout << "Memory alloc error!" << endl;
        return -1;
    }
    buf[0] = reg;
    buf[1] = value;
    (ssm_msg.msgs[0]).flags = 0;
    (ssm_msg.msgs[0]).addr = (unsigned short)slave;
    (ssm_msg.msgs[0]).buf = buf;
    (ssm_msg.msgs[0]).len = 2;
    ret = ioctl(i2cfd, I2C_RDWR, &ssm_msg);
    if (ret < 0) {
        printf("write error, ret=%#x, errorno=%#x, %s!\n", ret, errno, strerror(errno));
        free(ssm_msg.msgs);
        ssm_msg.msgs = NULL;
        return -1;
    }
    free(ssm_msg.msgs);
    ssm_msg.msgs = NULL;
    return 0;
}

int i2c2::i2c_read(unsigned char slave, unsigned char reg, unsigned char *buf)
{
    int ret;
    struct i2c_rdwr_ioctl_data ssm_msg = {0};
    unsigned char regs[2] = {0};
    regs[0] = reg;
    regs[1] = reg;
    ssm_msg.nmsgs = 2;
    ssm_msg.msgs = (struct i2c_msg *)malloc(ssm_msg.nmsgs * sizeof(struct i2c_msg));
    if (ssm_msg.msgs == NULL) {
        printf("Memory alloc error!\n");
        return -1;
    }
    (ssm_msg.msgs[0]).flags = 0;
    (ssm_msg.msgs[0]).addr = slave;
    (ssm_msg.msgs[0]).buf = regs;
    (ssm_msg.msgs[0]).len = 1;
    (ssm_msg.msgs[1]).flags = I2C_M_RD;
    (ssm_msg.msgs[1]).addr = slave;
    (ssm_msg.msgs[1]).buf = buf;
    (ssm_msg.msgs[1]).len = 1;
    ret = ioctl(i2cfd, I2C_RDWR, &ssm_msg);
    if (ret < 0) {
        printf("read data error,ret=%#x !\n", ret);
        free(ssm_msg.msgs);
        ssm_msg.msgs = NULL;
        return -1;
    }
    free(ssm_msg.msgs);
    ssm_msg.msgs = NULL;
    return 0;
}

i2c2::i2c2(/* args */)
{
}

i2c2::~i2c2()
{
    close(i2cfd);
}